import { Table, Icon, Row, Col, Button } from 'antd'
import { WeaTools, WeaCascader, WeaSelect, WeaError } from 'ecCom'
import equal from 'deep-equal';
import isFunction from 'lodash/isFunction';
import { Modal } from "antd";
import { toJS } from "mobx"
import './style/index.css';
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

class WeaPrjFieldSetTableEdit extends React.Component {
    
    select = new Array();
    cascader;

    constructor(props) {
        super(props);
        this.state = {
            columns: [],
            datas: [],
            selectedRowKeys: [],
            current: 1,
            showGroup: props.showGroup ? props.showGroup : false
        }
    }
    componentDidMount() {
        const { datas = [], columns = [] } = this.props;
        columns.length > 0 && this.setState(datas.length > 0 ? { datas: this.addKeytoDatas(datas), columns } : { columns })
    }

    componentWillReceiveProps(nextProps, nextState) {
        const _columns = nextProps.columns || [];
        const _showGroup = nextProps.showGroup || false;
        const _datas = nextProps.datas || [];
        !equal(_columns, this.props.columns) && this.setState({ columns: _columns });
        !equal(_showGroup, this.state.showGroup) && this.setState({ showGroup: _showGroup });
        if (!equal(_datas, this.state.datas)) {
            this.setState({ datas: this.addKeytoDatas(_datas) });
        }
    }
    addKeytoDatas(datas) {
        let _datas = datas.map((data, i) => {
            let _data = { ...data };
            _data.key = i;
            return _data
        })
        return _datas
    }
    render() {
        const { datas, showGroup, selectedRowKeys } = this.state;
        const { title, needAdd } = this.props;
        return (
            <div className="wea-cpt-table-edit-wf" >
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@z3eftp`} className="wea-title">
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@k6y05j`} span="20">
                        <div>{title}</div>
                    </Col>
                    {needAdd &&
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@kajxhb`} span="4" style={{ textAlign: "right", paddingRight: 10, fontSize: 12 }}>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@n00gdf`} type="primary" title={getLabel(1421, '新增')} size="small" onClick={this.doAdd}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@p96a4z`} type="plus" /></Button>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ib9xew`} type="primary" disabled={!`${selectedRowKeys}`} title={getLabel(91, '删除')} size="small" onClick={this.doDelete} ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@eiu3q4`} type="minus" /></Button>
                            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@1al7yy`} type={showGroup ? 'up' : 'down'} onClick={() => this.setState({ showGroup: !showGroup })} />
                        </Col>
                    }
                </Row>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@tyousk`} className="wea-content" style={{ display: showGroup ? "block" : "none" }}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@rz8upw`} span={24}>
                        <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@aaach7`}
                            columns={this.getColumns()}
                            dataSource={datas}
                            pagination={false}
                            rowSelection={needAdd ? this.getRowSelection() : false}
                            ref='edit'
                        />
                    </Col>
                </Row>

            </div>
        )
    }
    getColumns() {
        const { columns } = this.state;
        let _columns = [].concat(columns);
        _columns = _columns.map(col => {
            let _col = { ...col };

            _col.render = (text, record, index) => {
                return this.getColRender(_col, text, record, index);
            }
            return _col
        });
        return _columns
    }

    getColRender(_col, text, record, index) {
        const { com, isTask = false, useRecord = false, dataIndex, } = _col;
        const { wftype, notwfid } = this.props;
        const { datas } = this.state;
        let _com = [];
        let list = (useRecord && record.com ? record.com[dataIndex] : com) || [];
        list.map((c,i) => {
            if (typeof c.props === 'object') {
                _com.push(c);
            } else {
                let { key, label = '', type = 'INPUT', options = [], browserConditionParam = {}, innerStyle = { width: "100%" },
                    viewAttr = 2, showTime = false, format = "yyyy-MM-dd", compDef, onChange, otherParams, title } = c;
                const _type = type.toUpperCase();
                _com.push(
                    <span>
                        {_type === 'TEXT' && <span>{text}</span>
                        }
                        {_type === 'SELECT' && isTask &&//任务字段
                            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@p15dmf@${i}`}
                            ref={ (ref) => {
                                this.select.push(ref);
                            } }  
                            error={getLabel(385869,"此项必填")}
                            tipPosition="top"
                            style={{width:"100%"}}
                            >
                            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@tm2cle@${i}`}
                                {...otherParams}
                                defaultValue={record[key]}
                                value={record[key]}
                                options={options}
                                style={innerStyle}
                                viewAttr={viewAttr}
                                hasBorder={true}
                                onChange={value => this.onEdit({ record, index, key, value }, onChange, "getfield")}
                            />
                            </WeaError>
                        }
                        {_type === 'SELECT' && !isTask &&//wbs字段
                            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@ph8uvk@${i}`}
                            ref={ (ref) => {
                                this.select.push(ref);
                            } }  
                            error={getLabel(385869,"此项必填")}
                            tipPosition="top"
                            style={{width:"100%"}}
                            >
                            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@j06x87@${i}`}
                                {...otherParams}
                                defaultValue={record[key]}
                                value={record[key]}
                                options={options}
                                style={{ width: "95%" }}
                                viewAttr={viewAttr}
                                hasBorder={true}
                                onChange={value => this.onEdit({ record, index, key, value }, onChange)}
                            />
                            </WeaError>
                        }
                        {_type === 'CASCADER' &&
                            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@lv3zl5@${i}`}
                            ref={ (ref) => {
                                this.cascader=ref;
                            } }  
                            error={getLabel(385869,"此项必填")}
                            tipPosition="top"
                            style={{width:"100%"}}
                            >
                            <WeaCascader ecId={`${this && this.props && this.props.ecId || ''}_WeaCascader@j3bpjr@${i}`}
                                {...otherParams}
                                compDef={toJS(compDef)}
                                values={record[key]}
                                valueIsObject={true}
                                onChange={(value) => this.onEdit({ record, index, key, value }, onChange)}
                            />
                            </WeaError>
                        }
                    </span>
                )
            }
        });
        return (
            <div>
                {_com}
            </div>
        )
    }

    getBrowerDatas(record, key) {
        let replaceDatas = [];
        if (record[key + 'span'] !== undefined) {
            let keys = record[key].split(',');
            let values = record[key + 'span'].split(',');
            if (keys.length === values.length) {
                keys.map((k, i) => {
                    replaceDatas.push({ id: k, name: values[i] });
                });
            } else {
            }
        }
        return replaceDatas
    }
    getRowSelection() {
        const { columns, selectedRowKeys } = this.state;
        const { onRowSelect, getRowSelection } = this.props;
        if (!`${columns}`) return null;
        let rowSelection = {
            selectedRowKeys,
            onChange: (sRowKeys, selectedRows) => {
                this.setState({ selectedRowKeys: sRowKeys });
                typeof onRowSelect === 'function' && onRowSelect(sRowKeys, selectedRows);
            },
        };
        if (typeof getRowSelection === 'function') {
            rowSelection = getRowSelection(rowSelection);
        }
        return rowSelection;
    }

    onEdit({ record, index, key, value, names, bDatas }, onChange, api) {
        const { pageSize = 0, contentStore } = this.props;
        const { datas, current } = this.state;
        let _datas = [].concat(datas);
        _datas[pageSize * (current - 1) + index][key] = value;
        if (names) _datas[pageSize * (current - 1) + index][key + 'span'] = names;
        let fieldname = _datas[index]['taskfield'];
        const params = {fieldname: fieldname }

        if (api && api == "getfield") {
            WeaTools.callApi("/api/proj/prjutil/getWbsFieldNum", "POST", { ...params}).then((datas) => {
                const options = datas.options;
                _datas[index]["com"] = {
                    ..._datas[index]["com"],
                    "wbsfield": [{
                        "label": "",
                        "type": "SELECT",
                        "key": "wbsfield",
                        "editType": "3",
                        "options": options
                    }]
                }
                _datas[index]["wbsfield"] = "";
                this.setState({ datas: _datas });
            })
        }
        this.onChange(_datas);
        isFunction(onChange) && onChange(value, record, index, key);
    }

    doAdd = () => {
        let { datas, columns } = this.state;
        let _data = {};
        columns.forEach((col, index) => {
            const { com = [], useRecord = false, dataIndex } = col;
            com.map(c => {
                if (typeof c.props === 'object') {
                    return;
                }
                const { key: k, defaultValue } = c;
                k && (_data[k] = defaultValue || '');
            });
            _data.com = {
                ..._data.com,
                [dataIndex]: com
            }
            _data.viewAttr = "3";
        });
        let _datas = [].concat(datas);
        _datas.push(_data);
        this.setState({ datas: this.addKeytoDatas(_datas) });
        this.onChange(_datas);
    }

    doDelete = () => {
        const { datas, selectedRowKeys } = this.state;
        const _this = this;
        if (selectedRowKeys.length > 0) {
            Modal.confirm({
                title: getLabel(15172, '系统提示'),
                content: getLabel(83600, '确定要删除吗？'),
                onOk() {
                    let _datas = [].concat(datas);
                    selectedRowKeys.map(key => {
                        _datas = _datas.filter(data => data.key !== key)
                    });
                    _datas = _datas.map((data, i) => {
                        let _data = { ...data };
                        _data.key = i;
                        return _data
                    })
                    _this.setState({ datas: _datas, selectedRowKeys: [] });
                    _this.onChange(_datas);
                    typeof _this.props.onRowSelect === 'function' && _this.props.onRowSelect([]);
                },
                onCancel() { },
            });
        } else {
            Modal.info({
                title: getLabel(15172, '系统提示'),
                content: getLabel(32568, "请选择要删除的记录！")
            });
        }
    }
    onChange(datas) {
        const { columns } = this.state;
        let _datas = datas.map((data, i) => {
            let _data = { ...data }
            delete _data.key
            return _data
        })
        typeof this.props.onChange === 'function' && this.props.onChange(_datas, columns);
    }
    showErrors() {
		toJS(this.select).map(c => {
			if (c && !c.props.children.props.value && c.props.children.props.viewAttr == "3") {
				c.showError();
			}
        });
	}
    
}

export default WeaPrjFieldSetTableEdit;
